<?php

namespace addons\facrm;


use app\admin\model\facrm\Contract;
use app\common\library\Menu;
use fast\Tree;
use think\Addons;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;
use think\Queue;
use think\Cookie;

/**
 * 插件
 */
class Facrm extends Addons
{

    /**
     * 插件安装方法
     * @return bool
     */
    public function install()
    {
        $menu = [];
        $config_file = ADDON_PATH . "facrm" . DS . 'config' . DS . "menu.php";
        if (is_file($config_file)) {
            $menu = include $config_file;
        }
        if ($menu) {
            Menu::create($menu);
        }
		 /**
         * 增加手机号字段
         */
        $database=config('database');
        $isexits=Db::query("SELECT 1 FROM  information_schema.COLUMNS WHERE  table_name='{$database['prefix']}admin' AND COLUMN_NAME='mobile' limit 1");
        if (!$isexits){
            Db::query("ALTER TABLE {$database['prefix']}admin ADD mobile VARCHAR(20)  NULL COMMENT '手机'");
        }

        //首次安装创建表并导入测试数据
        \think\addons\Service::importsql('facrm');
        if (version_compare(config('fastadmin.version'), '1.3.0', '<') && Db::name("facrm_customer")->count() == 0) {
            $this->importData('testdata','');
        }
        return true;
    }

    /**
     * 插件卸载方法
     * @return bool
     */
    public function uninstall()
    {
        $info = get_addon_info('facrm');
        Menu::delete(isset($info['first_menu']) ? $info['first_menu'] : 'facrm');
        return true;
    }

    /**
     * 插件启用方法
     */
    public function enable()
    {
        $info = get_addon_info('facrm');
        Menu::enable(isset($info['first_menu']) ? $info['first_menu'] : 'facrm');
    }

    /**
     * 插件禁用方法
     */
    public function disable()
    {
        $info = get_addon_info('facrm');
        Menu::disable(isset($info['first_menu']) ? $info['first_menu'] : 'facrm');
    }

    /**
     * 插件升级方法
     */
    public function upgrade()
    {
        $menu = include ADDON_PATH . 'facrm' . DS . 'config' . DS . 'menu.php';
        Menu::upgrade('facrm', $menu);
        /**
         * 增加手机号字段
         */
        $database=config('database');
        $isexits=Db::query("SELECT 1 FROM  information_schema.COLUMNS WHERE  table_name='{$database['prefix']}admin' AND COLUMN_NAME='mobile' limit 1");
        if (!$isexits){
            Db::query("ALTER TABLE {$database['prefix']}admin ADD mobile VARCHAR(20)  NULL COMMENT '手机'");
        }
    }

    /**
     * 登录后 不跟进和未成交的客户处理
     */
    public function adminLoginInit()
    {
        $config = $this->getConfig();
        //不跟进 lose_day1  //不成交lose_day2

        if ($config['lose_day1'] > 0 || ($config['lose_day2'] > 0)) {
            $customerModel = model('\app\admin\model\facrm\Customer');
            $customerModel->where('deal_status', 0)->where('owner_user_id', '>', 0);
			
			 if ($config['lose_day1'] > 0 && $config['lose_day2'] > 0) {
                //如果不跟进和不成交都开启,掉入公海逻辑
                $customerModel->where(function ($query) use ($config) {
                    $query->where('follow_time', '<', (time() - $config['lose_day1'] * 86400))->whereOr('collect_time', '<', (time() - $config['lose_day2'] * 86400));
                });
            } elseif ($config['lose_day1'] > 0 && ($config['lose_day2'] <= 0)) {
                //如果只开启不跟进,掉入公海逻辑
                $customerModel->where('follow_time', '<', (time() - $config['lose_day1'] * 86400));
            } elseif ($config['lose_day1'] <= 0 && $config['lose_day2'] > 0) {
                //如果只开启不成交,掉入公海逻辑
                $customerModel->where('collect_time', '<', (time() - $config['lose_day2'] * 86400));
            } else {
                return true;
            }
			
            $lists = $customerModel->fetchSql(false)->select();
            if ($lists) {
                foreach ($lists as $row) {
                    $owner_user_id = $row->owner_user_id;
                    $row->discard();
                    \app\admin\model\AdminLog::create([
                        'title' => __("客户过期自动加入公海"),
                        'content' => json_encode(['id' => $row->id, 'name' => $row->name], JSON_UNESCAPED_UNICODE),
                        'url' => "customer/discard",
                        'admin_id' => $owner_user_id,
                    ]);
                }
            }
        }
    }


    /**
     * 登录后
     */
    public function adminLoginAfter($request){

        $exten_type=$request->request('exten_type','');
        $from_exten=$request->request('from_exten','','htmlentities');//工号
        \think\Cookie::set("facrm_extentype", $exten_type?$exten_type:'',86400 * 7);//云呼通话方式
        Cookie::set("facrm_from_exten", $from_exten?$from_exten:'',86400 * 7);
        if($from_exten){
            \app\admin\model\facrm\Cloudcall::edit('','',$from_exten,true);
        }

    }


    /**
     * 审核成功钩子
     * @param $param
     */
    public function facrmFlowVerify(&$param)
    {
        if (!isset($param['types'])) return false;
        $check_status=($param['is_end'] == 1&&$param['status']==1)?2:(($param['status']==0)?3:1);
        switch ($param['types']) {
            case 'receivables':
                if ($param['is_end'] == 1 && $param['status'] == 1) {
                    $receivablesModel = new \app\admin\model\facrm\contract\Receivables();
                    //$contractModel=new \app\admin\model\facrm\Contract();
                    $receivables = $receivablesModel::get($param['types_id']);
                    $receivables->contract()->setInc('return_money', $receivables->money);
                }
                //1审核中、2审核通过、3审核未通过
                break;
            case "contract":

                if ($param['is_end'] == 1 && $param['status'] == 1) {
                    $contractModel = new \app\admin\model\facrm\Contract();
                    $contract = $contractModel::get($param['types_id']);

                    $contract->customer()->update([
                        'deal_status' => 1, 'deal_time' => time(),
                        'purchase_times'=> Db::raw('purchase_times+1'),
                        'purchase_total'=> Db::raw('purchase_total+'.$contract->money),
                    ]);

                    //如果有商机也改成成交状态
                    if ($contract->business_id) {
                        $contract->business()->update(['is_end' => 1, 'deal_time' => time()]);//把商机改成成交状态
                    }

                }
                break;
            default:

        }
		 //消息通知
        try {
            Queue::push("addons\\facrm\\library\\notice\queue\\Flow" . ucfirst($param['types']) . "Job",
                ['model_id' => $param['types_id'], 'data' => ['check_status' => $check_status]]);
        } catch (\Exception $e) {

        }
        //消息通知end
		
        return true;

    }

    /**
     * 用户注册成功钩子
     */
    public function userRegisterSuccessed(&$user)
    {
       return \addons\facrm\library\Helper::synUser($user);
    }

    /**
     * 发送邮件成功钩子
     *param_data types类型如customer,contacts| typesid对应的ID
     *send_data发送邮件的内容
     *types_data 当前对象的数据
     * @param $param
     */
    public function facrmSendEmailSuccess($param)
    {
        if (!isset($param['param_data']) || !$param['param_data'] || !isset($param['send_data']) || !$param['send_data']) return false;
        return $this->addRecord($param['param_data'], $param['send_data'], __("发送邮件"));
    }


    /**
     * 发送短息成功钩子
     *param_data types类型如customer,contacts| typesid对应的ID
     *send_data发送短息的内容
     *types_data 当前对象的数据
     * @param $param
     */
    public function facrmSendSmsSuccess($param)
    {
        if (!isset($param['param_data']) || !$param['param_data'] || !isset($param['send_data']) || !$param['send_data']) return false;
        return $this->addRecord($param['param_data'], $param['send_data'], __("发送短息"));
    }

    /**
     * 自动添加跟进
     * @param $param_data
     * @param $send_data
     * @param string $df_content
     * @return bool
     * @throws \think\exception\DbException
     */
    private function addRecord($param_data, $send_data, $df_content = "")
    {
        $result = false;
        $record_data = array();
        if ($param_data && $param_data['types']) {
            switch ($param_data['types']) {
                case "customer":
                    //跟进客户
                    $customer = model('\app\admin\model\facrm\Customer');
                    $rowc = $customer->get($param_data['typesid']);
                    if (!$rowc) return false;
                    $rowc->follow_time = time();
                    $rowc->save();
                    $record_data['types'] = "customer";
                    $record_data['types_id'] = $rowc->id;
                    break;
                case "business":
                    $business = model('\app\admin\model\facrm\Business');
                    $row = $business->get($param_data['typesid']);
                    if (!$row) return false;
                    //更新客户表
                    $row->customer()->update(["follow_time" => time()]);
                    $row->save();
                    $record_data['types'] = "business";
                    $record_data['types_id'] = $row->id;
                    break;
                case "contacts":
                    //跟进客户
                    $contactsModel = model('\app\admin\model\facrm\customer\Contacts');
                    $contacts = $contactsModel->get($param_data['typesid']);
                    if (!$contacts || !$contacts->customer) return false;
                    $contacts->customer->follow_time = time();
                    $contacts->customer->save();
                    $record_data['types'] = "customer";
                    $record_data['types_id'] = $contacts->id;
                    break;
                case "clues":
                    //跟进线索
                    $cluesModel = model('\app\admin\model\facrm\Clues');
                    $rowc = $cluesModel->get($param_data['typesid']);
                    if (!$rowc) return false;
                    $rowc->follow_time = time();
                    $rowc->save();
                    $record_data['types'] = "clues";
                    $record_data['types_id'] = $rowc->id;
                    break;
                default:
                    break;
            }
        }
        if ($record_data) {
            model('\app\admin\model\facrm\Record')->allowField(true)->save(array_merge($record_data, [
                'content' => strip_tags(isset($send_data['content']) ? $send_data['content'] : $df_content),
                'record_type' => isset($send_data['record_type']) ? $send_data['record_type'] : 0,//跟进类型
                'create_user_id' => isset($send_data['create_user_id']) ? $send_data['create_user_id'] : 0,
            ]));
        }
        return $result;
    }

    /**
     * 导入数据
     */
    protected function importData($sqlname="",$dir='config')
    {
        $sqlFile = ADDON_PATH . 'facrm' . ($dir?DS.$dir:'').DS .$sqlname.'.sql';

        if (is_file($sqlFile)) {
            $lines = file($sqlFile);
            $templine = '';
            foreach ($lines as $line) {
                if (substr($line, 0, 2) == '--' || $line == '' || substr($line, 0, 2) == '/*') {
                    continue;
                }

                $templine .= $line;
                if (substr(trim($line), -1, 1) == ';') {
                    $templine = str_ireplace('__PREFIX__', config('database.prefix'), $templine);
                    $templine = str_ireplace('INSERT INTO ', 'INSERT IGNORE INTO ', $templine);
                    try {
                        Db::getPdo()->exec($templine);
                    } catch (\Exception $e) {
                        echo $e->getMessage();
                    }
                    $templine = '';
                }
            }
        }
    }

	 /**
     * 手机号脚本替换
     */
    public function viewFilter(& $content)
    {
        $module = strtolower(request()->module());
        $controller=strtolower(request()->controller());
        $action=strtolower(request()->action());
        if ($module == 'admin'&&$controller=='auth.admin') {
            $view=\think\View::instance();
            $mobile=isset($view->row->mobile)?$view->row->mobile:'';
            $str_rp='<div class="form-group hidden layer-footer">';
            $new_rp='<div class="form-group"><label for="mobile" class="control-label col-xs-12 col-sm-2">手机:</label><div class="col-xs-12 col-sm-8"><input type="mobile" class="form-control" id="mobile" name="row[mobile]" value="'.$mobile.'"  /></div></div>';
            $content = preg_replace_callback("/{$str_rp}/i", function ($matches)  use ($new_rp,$str_rp){
                return $new_rp.$str_rp;
            }, $content);
        }
        if ($module == 'admin'&&$controller=='index'&&$action=='index') {
            $view=\think\View::instance();
            if (!isset($view->auth)) return true;
            //获取合同\,回款待审批
            $contractModel= new Contract();
            $receivablesModel=new \app\admin\model\facrm\contract\Receivables();
            $invoiceModel=new \app\admin\model\facrm\Invoice();
        

            $filter_w['check_status'] =['in',[0,1]];
            $total = $contractModel->where($filter_w)->where('','exp','FIND_IN_SET('. $view->auth->id.',flow_admin_id)')->fetchSql(false)->count();
            $total +=$receivablesModel->where($filter_w)->where('','exp','FIND_IN_SET('.$view->auth->id.',flow_admin_id)')->fetchSql(false)->count();
            $total +=$invoiceModel->where($filter_w)->where('','exp','FIND_IN_SET('.$view->auth->id.',flow_admin_id)')->fetchSql(false)->count();


            $content =$content."<script>function setsidebar(){Backend.api.sidebar({'facrm/backlog':{$total},'facrm':{$total}})}; setTimeout('setsidebar()','5000');</script>";
        }
		 //云呼方式
        if ($module == 'admin'&&$controller=='index'&&$action=='login') {
			//获取云呼配置
            $all_types =  \addons\facrm\library\cloudcall\Call::getProviders();
            $keys = "";
            foreach ($all_types as $v) {
                $keys .= $keys ? ',' .'cloudcall'. $v : 'cloudcall' . $v;
            }
            $settingModel = new \app\admin\model\facrm\Setting();
            $setting= $settingModel->where('key', 'in', $keys)->where('status', 1)->find();//只找一条云呼通道
            if (!$setting) return true;
            $setting=$setting['values'];
			
            $exten_type=Cookie::get("facrm_extentype");//云呼通话方式
            $from_exten=htmlentities(Cookie::get("facrm_from_exten"));//云呼通话坐席工号
            $str_rp='<div class="form-group checkbox">';
            $new_rp="";
            if (isset($setting['open_exten'])&&$setting['open_exten']){
                $new_rp=' <div class="input-group">
                            <div class="input-group-addon"><span class="glyphicon fa fa-phone" aria-hidden="true"></span></div>
                            <input type="text" class="form-control"  placeholder="云呼工号，如不知道可留空" name="from_exten"  value="'.$from_exten.'" />
                        </div>';
            }

            $new_rp.=' <div class="input-group">
                            <div class="input-group-addon"><span class="glyphicon fa fa-phone" aria-hidden="true"></span></div>
                              <select class="form-control selectpicker"  name="exten_type"><option value=""> 请选择云呼方式</option>
                              <option value="Local" '.($exten_type=='Local'?'selected':'').'>工作手机</option>
                              <option value="sip" '.($exten_type=='sip'?'selected':'').'>软电话</option>
                              <option value="gateway" '.($exten_type=='gateway'?'selected':'').'>话机方式</option>
                              </select>  
                        </div>';
            $content = preg_replace_callback("/{$str_rp}/i", function ($matches)  use ($new_rp,$str_rp){
                return $new_rp.$str_rp;
            }, $content);
        }
    }

    /**
     * 发票开具钩子
     * @param $param
     */
    public function  facrmInvoiceOpener($param){
        //通知
        Queue::push("addons\\facrm\\library\\notice\queue\\InvoiceJob", [
            'model_id'=>$param['id'],
        ]);
    }
}
